const app = getApp()
const api = require('../../utils/api.js')
const mockData = require('../../utils/data.js')

const PLACEHOLDER_IMAGE = 'https://picsum.photos/seed/placeholder/800/600'
const USE_MOCK = false

function normalizeProduct(item = {}) {
  if (!item) {
    return null
  }

  const priceValue = item.marketPrice != null ? item.marketPrice : item.price
  const price = priceValue != null && priceValue !== ''
    ? Number(priceValue).toFixed(2)
    : '--'

  // 确保id字段正确映射（数据库返回的是productId，需要映射到id）
  const productId = item.productId != null ? item.productId : item.id

  return {
    id: productId,
    title: item.productName || item.title || '',
    location: item.city || item.destination || item.location || '',
    image: item.image || PLACEHOLDER_IMAGE,
    rating: item.rating != null ? Number(item.rating).toFixed(1) : '0.0',
    reviewCount: item.reviewCount != null ? item.reviewCount : 0,
    sales: item.salesCount != null ? item.salesCount : (item.sales != null ? item.sales : 0),
    price,
    originalPrice: item.originalPrice || '',
    productType: item.productType || 'normal',
    onlineAt: item.onlineAt ? item.onlineAt.split(' ')[0] : (item.earliestDate || ''),
    date: item.date || ''
  }
}

Page({
  data: {
    product: null,
    selectedPackage: null,
    packages: [],
    reviews: [],
    avgRating: 0,
    imageReviewCount: 0,
    isFavorite: false,
    showRules: false,
    loading: false
  },
  
  onLoad(options) {
    const id = parseInt(options.id, 10)
    if (!id) {
      wx.showToast({
        title: '商品不存在',
        icon: 'none'
      })
      return
    }
    this.loadProduct(id)
    // loadReviews 会在 loadProduct 成功后调用
  },
  
  loadProduct(id) {
    this.setData({ loading: true })
    if (USE_MOCK) {
      const fallback = (mockData.products || []).find(item => item.id === id) || (mockData.products || [])[0]
      const product = normalizeProduct(fallback)
      this.setData({
        product,
        packages: [],
        selectedPackage: null,
        isFavorite: app.isFavorite(id),
        loading: false
      })
      app.addToBrowsingHistory(product)
      wx.setNavigationBarTitle({
        title: product.title.length > 10 ? product.title.substring(0, 10) + '...' : product.title
      })
      // 加载评论
      this.loadReviews()
      return
    }
    api.getProductDetail(id).then(data => {
      const product = normalizeProduct(data)
      if (!product) {
        throw new Error('未获取到商品信息')
      }
      this.setData({
        product,
        packages: [],
        selectedPackage: null,
        isFavorite: app.isFavorite(id),
        loading: false
      })
      
      app.addToBrowsingHistory(product)
      
      wx.setNavigationBarTitle({
        title: product.title.length > 10 ? product.title.substring(0, 10) + '...' : product.title
      })
      
      // 加载评论
      this.loadReviews()
    }).catch(err => {
      console.error('加载产品详情失败:', err)
      const fallback = (mockData.products || []).find(item => item.id === id)
      if (fallback) {
        wx.showToast({
          title: '使用示例商品数据',
          icon: 'none'
        })
        const product = normalizeProduct(fallback)
        this.setData({
          product,
          packages: [],
          selectedPackage: null,
          isFavorite: app.isFavorite(id),
          loading: false
        })
        app.addToBrowsingHistory(product)
        wx.setNavigationBarTitle({
          title: product.title.length > 10 ? product.title.substring(0, 10) + '...' : product.title
        })
        // 加载评论
        this.loadReviews()
      } else {
        wx.showToast({
          title: '产品信息加载失败',
          icon: 'none'
        })
        this.setData({ loading: false })
      }
    })
  },
  
  loadReviews() {
    if (!this.data.product || !this.data.product.id) {
      return
    }
    
    const productId = this.data.product.id
    
    // 同时获取评论列表和统计信息
    Promise.all([
      api.getProductReviews(productId),
      api.getProductReviewStats(productId)
    ])
      .then(([reviews, stats]) => {
        console.log('获取评论成功:', reviews)
        console.log('获取评论统计成功:', stats)
        
        // 标准化评论数据
        const normalizedReviews = (reviews || []).map(review => {
          // 处理图片（如果是逗号分隔的字符串，转换为数组）
          let imageList = []
          if (review.images) {
            if (typeof review.images === 'string') {
              imageList = review.images.split(',').filter(img => img.trim() !== '')
            } else if (Array.isArray(review.images)) {
              imageList = review.images
            }
          }
          
          // 格式化日期
          let dateStr = ''
          if (review.reviewTime) {
            const date = new Date(review.reviewTime)
            const month = date.getMonth() + 1
            const day = date.getDate()
            dateStr = `${month}月${day}日`
          } else if (review.createTime) {
            const date = new Date(review.createTime)
            const month = date.getMonth() + 1
            const day = date.getDate()
            dateStr = `${month}月${day}日`
          }
          
          return {
            id: review.reviewId || review.id,
            user: review.userName || '匿名用户',
            avatar: review.userAvatar || 'https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?w=100&h=100&fit=crop',
            rating: review.rating || 5,
            content: review.content || '',
            images: imageList,
            date: dateStr
          }
        })
        
        // 计算平均评分和带图评论数
        const avgRating = stats && stats.avgRating ? Number(stats.avgRating).toFixed(1) : '0.0'
        const imageReviewCount = stats && stats.imageCount ? stats.imageCount : normalizedReviews.filter(r => r.images && r.images.length > 0).length
        
        this.setData({
          reviews: normalizedReviews,
          avgRating: avgRating,
          imageReviewCount: imageReviewCount
        })
      })
      .catch(err => {
        console.error('获取评论失败:', err)
        // 失败时使用空数组
        this.setData({
          reviews: [],
          avgRating: '0.0',
          imageReviewCount: 0
        })
      })
  },
  
  selectPackage(e) {
    const index = e.currentTarget.dataset.index
    this.setData({
      selectedPackage: this.data.packages[index]
    })
  },
  
  toggleFavorite() {
    if (!this.data.product) {
      return
    }

    const isFavorite = !this.data.isFavorite
    this.setData({ isFavorite })
    
    if (isFavorite) {
      app.addToFavorites(this.data.product)
      wx.showToast({
        title: '已收藏',
        icon: 'success'
      })
    } else {
      app.removeFromFavorites(this.data.product.id)
      wx.showToast({
        title: '已取消收藏',
        icon: 'none'
      })
    }
  },
  
  share() {
    wx.showShareMenu({
      withShareTicket: true
    })
  },
  
  goToOrderConfirm() {
    if (!this.data.product) {
      wx.showToast({
        title: '未找到商品信息',
        icon: 'none'
      })
      return
    }

    const productId = this.data.product.id
    const packageId = this.data.selectedPackage ? this.data.selectedPackage.date : ''
    const url = `/pages/order-confirm/order-confirm?productId=${productId}${packageId ? `&packageId=${packageId}` : ''}`
    wx.navigateTo({ url })
  },
  
  goToAllReviews() {
    wx.navigateTo({
      url: `/pages/reviews/reviews?productId=${this.data.product.id}`
    })
  },
  
  toggleRules() {
    this.setData({
      showRules: !this.data.showRules
    })
  },
  
  scrollToTop() {
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300
    })
  }
})


